package com.itheima.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service

public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;
    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
        // //1. 设置分页参数
        // PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        //
        // //2. 执行查询
        // List<Emp> empList = empMapper.list(empQueryParam);
        // Page<Emp> p = (Page<Emp>) empList;
        //
        // //3. 封装分页结果
        // return new PageResult<>(p.getTotal(), p.getResult());

        Page<Emp> page = Page.of(empQueryParam.getPage(),empQueryParam.getPageSize());
        //执行分页查询
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotEmpty(empQueryParam.getName()),Emp::getName,empQueryParam.getName())
                .eq(empQueryParam.getGender()!=null,Emp::getGender,empQueryParam.getGender())
                .between(empQueryParam.getBegin()!=null && empQueryParam.getEnd()!=null,
                        Emp::getEntryDate,empQueryParam.getBegin(),empQueryParam.getEnd());
        page = page(page,queryWrapper);

        //部门名称为空，需要赋值
        List<Emp> empList = page.getRecords();
        //获取部门id
        List<Integer> deptIds = empList.stream().map(emp -> emp.getDeptId()).collect(Collectors.toList());
        //根据部门id拉取部门列表信息
        List<Dept> deptList = deptService.listByIds(deptIds);
        if(!deptList.isEmpty())
        {
           empList.forEach(emp -> {
               deptList.stream().filter(dept ->
                       dept.getId().equals(emp.getDeptId())).findFirst()
                       .ifPresent(dept -> emp.setDeptName(dept.getName()));
           });
        }
        return new PageResult<>(page.getTotal(), page.getRecords());
    }
    @Autowired
    private EmpLogService empLogService;

    @Transactional(rollbackFor = Exception.class) //开启事务管理 - rollbackFor: 抛出什么异常回滚事务
    @Override
    public void saveEmp(Emp emp) {
        //1. 保存员工的基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        // empMapper.insert(emp);
        save(emp); //mybatis plus 的实现类方法 ServiceImpl
        log.info("保存员工信息, {}", emp);

        //2. 保存员工的工作经历信息 --> 属于上面刚添加的员工的
        List<EmpExpr> exprList = emp.getExprList();
        if(exprList != null && !exprList.isEmpty()){ //有工作经历
            //遍历集合，设置员工id
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.saveBatch(exprList);
        }

    }

    @Override
    public List<Emp> list() {
        return empMapper.list(null);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteEmp(List<Integer> ids) {
        //1. 删除员工的基本信息
        log.info("删除员工的基本信息:{}",ids);
        // ids.forEach(id->
        // {
        //     removeById(id);
        // });
        removeBatchByIds(ids);
        //2. 删除员工的工作经历信息
        //2.1 需要判断该员工是否有员工经历
        LambdaQueryWrapper<EmpExpr> empExprLambdaQueryWrapper = new LambdaQueryWrapper<>();
        empExprLambdaQueryWrapper.in(EmpExpr::getEmpId,ids);
        long count = empExprService.count(empExprLambdaQueryWrapper);
        if(count>0) {
            empExprService.remove(empExprLambdaQueryWrapper);
        }
    }

    @Override
    public Emp getByIdEmp(Integer id) {
        Emp emp = getById(id);
        Integer empId= emp.getId();
        LambdaQueryWrapper<EmpExpr> empExprLambdaQueryWrapper = new LambdaQueryWrapper<>();
        empExprLambdaQueryWrapper.eq(EmpExpr::getEmpId,empId);
        //根据id去查找工作经历列表
        List<EmpExpr> empExprs = empExprService.list(empExprLambdaQueryWrapper);
        emp.setExprList(empExprs);
        return emp;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Emp emp) {
        //1. 根据ID更新员工基本信息
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);

        //2. 更新员工的工作经历信息(先删除, 再添加)
        //2.1 根据员工的id删除员工的工作经历
        // empExprMapper.deleteByEmpIds(Arrays.asList(emp.getId()));
        Integer empId= emp.getId();
        LambdaQueryWrapper<EmpExpr> empExprLambdaQueryWrapper = new LambdaQueryWrapper<>();
        empExprLambdaQueryWrapper.eq(EmpExpr::getEmpId,empId);
        empExprService.remove(empExprLambdaQueryWrapper);
        //2.2 再添加员工的工作经历 (批量)
        List<EmpExpr> exprList = emp.getExprList();
        if(exprList != null && !exprList.isEmpty()){ //有工作经历
            //遍历集合，设置员工id
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    public JobOption getEmpJobData() {
        // [{pos=教研主管, num=1} {pos=讲师, num=14}  {pos=学工主管, num=1} ...]
        List<Map> jobDataList = empMapper.getEmpJobData();

        // 组装数据 JobOption
        List jobList = jobDataList.stream().map(map -> {
            return map.get("pos");
        }).toList();

        List dataList = jobDataList.stream().map(map -> {
            return map.get("num");
        }).toList();
        return new JobOption(jobList, dataList);
    }


    @Override
    public List<Map<String, Object>> getEmpGenderData() {
        List<Map<String, Object>> mapList = empMapper.getEmpGenderData();
        return mapList;
    }

    /**
     * 根据用户名与密码查询员工登录信息
     * ctrl+Alt+鼠标点击，直接进入实现类重写方法中
     * @param emp
     * @return
     */
    @Override
    public LoginInfo getLoginInfo(Emp emp) {
        //1.根据用户名与密码查询员工信息Emp对象
        Emp e = empMapper.findByUserNameAndPwd(emp);

        if(e!=null) {
            //2.实例LoginInfo对象，封装数据返回
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setId(e.getId());
            loginInfo.setUsername(e.getUsername());
            loginInfo.setName(e.getName());

            //定义载荷
            Map<String,Object> claims = new HashMap<>();
            claims.put("id", e.getId());
            //调用工具类生成令牌
            String token = JwtUtils.generateJwt(claims);
            //封装令牌
            loginInfo.setToken(token);
            return loginInfo;
        }
        return null; //没有找到登录的员工
    }


}
